﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sinacor.Infra.Common.Exceptions;
using Sinacor.Infra.Common.Validation;
using PSE.Framework.UI.Resources;

namespace Sinacor.Infra.UI.Exceptions
{
    public class ErrorMessage
    {
        public static void ConfigureExceptionMessage(Exception exception)
        {
            try
            {
                string errorMessage;

                // Capturando provider de recursos
                IResourceProvider resourceProvider = ResourceProviderManager.GetResourceProvider();

                if (exception is ValidationException)
                {
                    foreach (ValidationError validationError in ((ValidationException)exception).ValidationErrors.Values)
                    {
                        errorMessage = (string)resourceProvider.TryGetResource(validationError.ResourceKey, validationError.Parameters.ToArray());

                        validationError.ConfigureMessage(errorMessage);
                    }

                    ((ValidationException)exception).ConfigureMessage();
                }
                else if (exception is BaseErrorNumberException)
                {
                    object[] parameters = new object[0];

                    if (exception is BusinessException)
                        parameters = ((BusinessException)exception).Parameters.ToArray();

                    errorMessage = (string)resourceProvider.TryGetResource(((BaseErrorNumberException)exception).ResourceKey, parameters);

                    ((BaseErrorNumberException)exception).ConfigureMessage(errorMessage);
                }
            }
            catch (Exception ex)
            {
                if (exception != null && exception.Data != null)
                    exception.Data.Add("ConfigureExceptionMessageError", ex.ToString());
            }
        }
    }
}
